import CryptoJS from 'crypto-js';

import { JsonFormatter } from './JsonFormatter';

function encrypt(key: string, iv: string, plain: string): string {
  const useKey = CryptoJS.enc.Utf8.parse(key);
  const useIv = CryptoJS.enc.Utf8.parse(iv);

  let cipherParams = CryptoJS.AES.encrypt(plain, useKey, {
    iv: useIv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
    format: JsonFormatter,
  });

  const text = CryptoJS.enc.Base64.stringify(cipherParams.ciphertext);

  return text;
}

function decrypt(key: string, iv: string, cipher: string) {
  const useKey = CryptoJS.enc.Utf8.parse(key);
  const useIv = CryptoJS.enc.Utf8.parse(iv);

  const parsed = CryptoJS.enc.Base64.parse(cipher);
  const decoded = CryptoJS.enc.Base64.stringify(parsed);
  const data = CryptoJS.AES.decrypt(decoded, useKey, {
    iv: useIv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  const jsonStr = data.toString(CryptoJS.enc.Utf8);
  return JSON.parse(jsonStr);
}

export { encrypt, decrypt };
